﻿// COPYRIGHT 2012, Justin Michalczak
//
// This file is licenced to the public under the Apache
// License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CopperVineSoftware.Stackr.Parser.Lexemes;

namespace CopperVineSoftware.Stackr.Parser
{
    /// <summary>Main entry point into the Stackr Parser library.</summary>
    public sealed class Parser
    {
        /// <summary>Parses text into a program.</summary>
        /// <param name="programText">Text to parse.</param>
        /// <returns>The parsed program.</returns>
        /// <exception cref="ArgumentNullException">If the <paramref name="programText"/> parameter is <c>null</c> or empty.</exception>
        /// <exception cref="SyntaxException">If there was a syntax error in the program.</exception>
        /// <exception cref="DuplicateDefinitionException">If there were duplicate definitions in the program.</exception>
        /// <exception cref="NoMainFunctionDefinedException">If the program does not define a main function.</exception>
        public static Program Parse(string programText)
        {
            if (string.IsNullOrEmpty(programText))
                throw new ArgumentNullException("programText");

            LexemeParser lexemeParser = new LexemeParser();
            var lexemeMatch = lexemeParser.GetMatch(programText, lexemeParser.Program);

            if (!(lexemeMatch.Success))
            {
                int preIndex = Math.Max(0, lexemeMatch.ErrorIndex - 10);
                int preLength = lexemeMatch.ErrorIndex - preIndex;

                int postIndex = Math.Min(programText.Length, lexemeMatch.ErrorIndex + 10);
                int postLength = postIndex - lexemeMatch.ErrorIndex;

                string location = string.Format("{0}[{1}]{2}", programText.Substring(preIndex, preLength), programText[lexemeMatch.ErrorIndex], programText.Substring(lexemeMatch.ErrorIndex + 1, postLength));
                throw new SyntaxException(lexemeMatch.Error, location);
            }

            IEnumerable<Definition> programDefinitions = lexemeMatch.Results.Cast<Definition>();
            return new Program(programDefinitions);
        }

        private Parser()
        {
        }
    }
}
